<!--添加农户信息-->

<script setup lang="ts">
import { ref, reactive, getCurrentInstance, onMounted, onBeforeMount } from "vue";
import HzBaseFrom from "@/views/credit/peasants/pea-message/components/hzBaseFrom.vue";
import { reqCreAdd, reqUploadImage } from "@/api/credit/peasants/pea-message";
import { useRoute } from "vue-router";
import { reqCrePeaInfoByHzId, reqCreEdit } from "@/api/credit/peasants/pea-message";
import HzFamilyNumberFrom from "@/views/credit/peasants/pea-message/components/hzFamilyNumberFrom.vue";
import HzFamFaZhanFrom from "@/views/credit/peasants/pea-message/components/hzFamFaZhanFrom.vue";
import Vue3Esign from "@/components/Vue3Esign/index.vue";
import { ElMessage, FormInstance } from "element-plus";
import { base64ImgtoFile } from "@/utils/imageUtil";
import { useTagsViewStore } from "@/store/modules/tagsView";
/*农户表单*/
// 表单
const peaFrom = reactive({
  //////////////////////////////////////////////////////////////////////////////
  /*户主基本信息表*/
  hzId: "",

  hzName: "", //户主姓名
  hzSex: "",
  hzAge: "", //年龄
  hzPhoneNumber: "", //手机号码（户主）

  hzIdCardNumber: "", //身份证号码（户主）
  xingZhengArea: [], // 行政区域


  familyAddress: "", //家庭详细住址
  hzMarriage: "", //婚姻状况  点选择
  hzNation: "", //民族    下拉框选择

  hzIdCardFront: "", //身份证正面（户主） 单张照片地址
  hzIdCardReverse: "", //身份证反面（户主） 单张照片地址
  hzAddressPho: "", //户口住址页（户主） 单张照片地址

  hasInVillager: "", //是否为本村人   点选择
  familySize: "", //家庭人数  数字输入框
  familyLoaderSize: "", //家庭劳动力人数  数字输入框
  hasIll: "", //家庭成员是否有重疾病患者（长期住院或接受治疗） 点选择

  farmerType: [], //农户类型  多选框
  hasPingKunHu: "", //是否建档贫困户 单点选择
  maxXueLi: "", //家庭最高学历 下拉框

  hasLand: "", //是否有农村土地经营证书
  landArea: "", //承包面积（亩）
  canQuanNum: "", // 产权证编号

  landPho: [], //土地经营证书照片

  hasTransLand: "", //是否流转土地
  transArea: "", // 流转面积（亩）
  treeArea: "", // 山林面积
  treeDeedNum: "", //林权证编号
  treeDeedPho: [], // 林权证图片

  hasFrameHouse: "", // 是否有农房
  newDanger: "", // 农房新旧程度
  houseJieGou: "", // 农房结构
  houseHeight: "", // 农房楼层
  houseArea: "", // 农房面积


  //////////////////////////////////////////////////////////////////////////////
  /*家庭成员信息*/
  peaHzFamList: [], //家庭成员

  //////////////////////////////////////////////////////////////////////////////
  /*家庭产业状况*/

  mainYeWuYear: "", //主营业务经营年限       main_pro_years
  mainYeWuXiaQu: [], //主项目经营辖区        main_pro_area
  mainXiangMuAddress: "", //主要项目经营地址
  mainChanYe: [], //家庭主产业（多选） 种植，养殖，其他 fam_main_pro

  hasZaiHai: "", //近三年来生产是否受灾
  laoDongJiNeng: "", //劳动技能

  farming: [], //养殖项目
  croping: [], //种植项目

  famWuGongIncome: "", //家庭务工收入（元）
  famOtherIncome: "", // 家庭其他收入（元）

  shengChanExpend: "", // 生产支出/年(元)
  lifeExpend: "", // 家庭生活支出/年(元)

  hasLoans: "", //是否有金额贷款意向
  loansMoney: "", //意向贷款金额(元)


  //////////////////////////////////////////////////////////////////////////////
  /*签字确认后进行提交*/
  signUrl: "",

  ratingStatus: "0"
});



// 重置数据
const reset = () => {
  Object.keys(peaFrom).forEach((key) => {
    if(key == "xingZhengArea"
      || key == "farmerType"
      || key == "landPho"
      || key == "treeDeedPho"
      || key == "peaHzFamList"
      || key == "mainXiangMuAddress"
      || key == "mainChanye"
      || key == "farming"
      || key == "croping"
    ) peaFrom[key] = []
    else if(key == "ratingStatus") peaFrom[key] = "0"
    else peaFrom[key] = ""
  })
};



const { proxy }: any = getCurrentInstance();
const activeName = ref("first");
const $route = useRoute();
const TagsViewStore = useTagsViewStore();
const loading = ref(true); // 加载...
const hzBaseFromRef = ref();// 农户基本信息
const hzFamilyNumberFromRef = ref(); // 农户家庭信息
const hzFamFaZhanFromRef = ref(); // 农户发展产业


// 表单组件验证并提交
const onSubmitForm = async () => {
  // 做验证并开始评分
  try {
    await hzBaseFromRef.value.submitHzForm();
    await hzFamilyNumberFromRef.value.submitHzFamNumForm();
    await hzFamFaZhanFromRef.value.submitHzFamInForm();
    console.log(121);
    if(peaFrom.peaHzFamList.length != peaFrom.familySize){
      proxy.$modal.msgError("请检查添加的家庭成员人数是否和填写的一致！");
      return
    }
    if(peaFrom.signUrl == ""){
      proxy.$modal.msgError("请签名后再提交！");
      return
    }

    proxy.$modal.confirm("提交之后信息无法进行更改！").then(async () => {
        peaFrom.ratingStatus = "1";
        // 如果若错误会直接抛出
        if (peaFrom.hzId == undefined) {
          await reqCreAdd(peaFrom).then(async (req: reqBaseData) => {
            if (req.code == 200) {
              proxy.$modal.msgSuccess("提交成功，开始进行评议！");
              // 关闭该模块
              await handleClose()
            } else {
              proxy.$modal.msgError("提交失败，请稍后重试！");
            }
          }).catch((e) => {
          });
        } else {
          await reqCreEdit(peaFrom).then((req: reqBaseData) => {
            if (req.code == 200) {
              proxy.$modal.msgSuccess("提交成功，开始进行评议！");
            } else {
              proxy.$modal.msgError("提交失败，请稍后重试！");
            }
          }).catch((e) => {
          });
        }
      }
    );
  } catch (e) {
    console.log(e);
    proxy.$modal.msgError(e);
  }
};

// 提交数据
const handleSubmit = async (type: string) => {
  // 不做验证将数据保存到数据库中
  if (type == "add" && peaFrom.hzId == undefined) {
    await reqCreAdd(peaFrom).then((req: reqBaseData) => {
      if (req.code == 200) {
        proxy.$modal.msgSuccess("保存成功！");
        handleClose();
      } else {
        proxy.$modal.msgError("保存失败，请稍后重试！");
      }
    }).catch((e) => {
    });
  } else if (type == "add" && peaFrom.hzId != undefined) {
    await reqCreEdit(peaFrom).then((req: reqBaseData) => {
      if (req.code == 200) {
        proxy.$modal.msgSuccess("保存成功！");
      } else {
        proxy.$modal.msgError("保存失败，请稍后重试！");
      }
    }).catch((e) => {
    });
  }
};

// 组件挂载完成后执行的函数
onBeforeMount(async () => {
  loading.value = true;
  await init();
});

// 初始化函数
const init = async () => {
  const hzId = $route.params && $route.params.hzId;
  if (hzId != 0) {
    // 表示是修改操作
    peaFrom.hzId = hzId;
    // 进行查询
    await reqCrePeaInfoByHzId(hzId).then((req) => {
      // 进行数据的赋值
      Object.keys(peaFrom).forEach(key => {
        peaFrom[key] = req.data[key];
      });
    });
  }
  setTimeout(() => {
    loading.value = false;
  }, 1000);
};

// 关闭该路由组件
const isActive = (path) => {
  return path === $route.path;
};

const handleClose = async () => {
  const activeTabPath = $route.path;
  if (isActive(activeTabPath)) {
    toLastView(activeTabPath);
  }
  await TagsViewStore.delView(activeTabPath);
};

function toLastView(activeTabPath) {
  console.log(activeTabPath);
  let index = TagsViewStore.visitedViews.findIndex((item) => item.path === activeTabPath);
  const nextTab = TagsViewStore.visitedViews[index + 1] || TagsViewStore.visitedViews[index - 1];
  if (!nextTab) return;
  router.push(nextTab.path);
  TagsViewStore.addVisitedView(nextTab);
}


const lineWidth = ref(6);
const lineColor = ref("#409eff");
const bgColor = ref("");
const isCrop = ref(false);
const ruleFormRef = ref<FormInstance>();

const esginRef: any = ref(null);
const handleReset = () => {
  esginRef.value.reset();
};
const handleGenerate = async () => {
  await esginRef.value
    .generate()
    .then(async (res) => {
      //生成base64编码
      // 这里需要将其上传到服务器
      // 将 Base64 编码字符串解码为二进制数据
      let imgFile = base64ImgtoFile(res);
      /*将file进行上传*/
      const form = new FormData();
      form.set("file", imgFile);
      // 将该文件进行上传
      await reqUploadImage(form)
        .then((req) => {
          if (req.code == 200) {
            ElMessage.success("上传成功");
            // 将图片的地址进行输出
            peaFrom.signUrl = req.fileName;
          }
        })
        .catch((err) => {
          console.log("reqUploadImage", err);
        });

    })
    .catch((err) => {
      ElMessage.warning(err); // 画布没有签字时会执行这里 'Not Signned'
    });
};

</script>

<template>
  <PageWrapLayout>
    <!--下面是一个表单进行数据的收集      -->
    <div class="el-body" v-loading="loading">
      <div class="utils">
        {{ peaFrom }}
        <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
          <el-tab-pane label="户主信息采集" name="first" class="dashed-border">
            <el-scrollbar :noresize="true" height="100%" class="hide-scrollbar">
              <hzBaseFrom style="width: 95%;" ref="hzBaseFromRef" v-model:peaFrom="peaFrom"></hzBaseFrom>
            </el-scrollbar>
          </el-tab-pane>

          <el-tab-pane label="家庭成员信息" name="second" class="dashed-border">
            <el-scrollbar :noresize="true" height="100%" class="hide-scrollbar">
              <hzFamilyNumberFrom ref="hzFamilyNumberFromRef"
                                  v-model:peaHzFamList="peaFrom.peaHzFamList"
                                  v-model:familySize="peaFrom.familySize" :hz-id="peaFrom.hzId"></hzFamilyNumberFrom>
            </el-scrollbar>
          </el-tab-pane>

          <el-tab-pane label="家庭产业发展情况" name="third" class="dashed-border">
            <el-scrollbar :noresize="true" height="100%" class="hide-scrollbar">
              <hzFamFaZhanFrom ref="hzFamFaZhanFromRef" v-model:peaFrom="peaFrom"></hzFamFaZhanFrom>
            </el-scrollbar>
          </el-tab-pane>

          <el-tab-pane label="签字确认" name="fourth" class="dashed-border">
            <!-- 召唤签字框进行签字     -->
            <el-scrollbar :noresize="true" height="100%" class="hide-scrollbar">
              <el-divider content-position="left">签字图片展示</el-divider>
              <el-image class="el-image-s" :src="proxy.$getServerUrl() + peaFrom.signUrl"></el-image>
              <el-divider content-position="left">签字区域 ---- 温馨提示：请在签完字后点击保存，否则将不会被修改掉
              </el-divider>
              <div class="vue3Esign">
                <div class="el-button-in">
                  <el-button type="warning" @click="handleReset">清空</el-button>
                  <el-button type="success" @click="handleGenerate">保存</el-button>
                </div>
                <Vue3Esign
                  ref="esginRef"
                  v-model:bg-color="bgColor"
                  :width="1000"
                  :height="500"
                  :is-crop="isCrop"
                  :line-width="lineWidth"
                  :line-color="lineColor"
                  class="esign"
                ></Vue3Esign>
              </div>
            </el-scrollbar>
          </el-tab-pane>
        </el-tabs>
      </div>
      <div class="last-page">
        <el-space wrap :size="35">
          <el-button type="warning" @click="reset">重置</el-button>
          <el-button type="primary" @click="handleSubmit('add')">保存</el-button>
          <el-button type="success" @click="onSubmitForm">提交</el-button>
        </el-space>
        <el-button type="danger" @click="handleClose">取消</el-button>
      </div>
    </div>
  </PageWrapLayout>
</template>

<style scoped lang="scss">
@import "./index";


.el-body {
  padding: 5px;
  width: calc(100% - 10px);

  .utils {
    width: 100%;
  }

  .el-tab-pane {
    width: 100%;
    height: calc(100vh - 300px);
  }

  .dashed-border {
    width: calc(100% - 32px);
    border: 1px dashed black;
    padding: 15px;
  }

  .last-page {
    //position: fixed;
    margin-top: 20px;
    bottom: 20px;
    right: 30px;
    margin-bottom: 10px;
    margin-right: 10px;
    display: flex;
    justify-content: right;
  }

}

.esign {
  border: black 1px dashed;
}

.el-form {
  font-weight: bold;
}

.el-dialog__title {
  font-weight: bold;
}

.el-image-s {
  border: black 1px dashed;
}

.vue3Esign {

  .esign {
  }

  .el-button-in {
    margin: 20px 20px;
  }
}
</style>
